<template>
  <div class="profile">
    <div class="page-header">
      <h1>个人资料</h1>
    </div>

    <el-card>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="large">
        <el-form-item label="头像">
          <div class="avatar-section">
            <el-avatar :size="80" :src="form.avatar">
              {{ form.nickname || form.username }}
            </el-avatar>
            <div class="avatar-actions">
              <el-upload
                :show-file-list="false"
                :before-upload="handleAvatarUpload"
                accept="image/*"
              >
                <el-button type="primary">更换头像</el-button>
              </el-upload>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" maxlength="20" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="请输入昵称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="form.bio"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading"> 保存修改 </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { uploadFile } from '@/api/file'

const authStore = useAuthStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive({
  username: '',
  email: '',
  nickname: '',
  avatar: '',
  bio: ''
})

// 表单验证规则
const rules: FormRules = {
  nickname: [{ max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }],
  bio: [{ max: 500, message: '个人简介长度不能超过500个字符', trigger: 'blur' }]
}

// 头像上传
const handleAvatarUpload: UploadProps['beforeUpload'] = async (file) => {
  try {
    const response = await uploadFile(file)
    form.avatar = response.file_url
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
  }
  return false // 阻止默认上传行为
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 调用更新用户资料的API
    const updateData = {
      nickname: form.nickname,
      avatar: form.avatar,
      bio: form.bio,
      email: form.email
    }

    await authStore.updateProfile(updateData)
    ElMessage.success('资料更新成功')
  } catch (error) {
    console.error('更新资料失败:', error)
    ElMessage.error('更新资料失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (authStore.user) {
    form.username = authStore.user.username
    form.email = authStore.user.email
    form.nickname = authStore.user.nickname || ''
    form.avatar = authStore.user.avatar || ''
    form.bio = authStore.user.bio || ''
  }
}

// 初始化数据
onMounted(() => {
  handleReset()
})
</script>

<style lang="scss" scoped>
.profile {
  .page-header {
    margin-bottom: 20px;

    h1 {
      margin: 0;
      color: var(--text-primary);
    }
  }

  .avatar-section {
    display: flex;
    align-items: center;
    gap: 20px;

    .avatar-actions {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
  }
}
</style>
